<?php

/**
	* The short description
	*
	* As many lines of extendend description as you want {@link element} links to an element
	* {@link http://www.example.com Example hyperlink inline link} links to a website. The inline
	* source tag displays function source code in the description:
	* {@source } 
	* 
	* In addition, in version 1.2+ one can link to extended documentation like this
	* documentation using {@tutorial phpDocumentor/phpDocumentor.howto.pkg}
	* In a method/class var, {@inheritdoc may be used to copy documentation from}
	* the parent method
	* {@internal 
	* This paragraph explains very detailed information that will only
	* be of use to advanced developers, and can contain
	* {@link http://www.example.com Other inline links!} as well as text}}
	*
	* Here are the tags:
	*
	* @abstract
	* @access       public or private
	* @author       author name <author@email>
	* @copyright    name date
	* @deprecated   description
	* @deprec       alias for deprecated
	* @example      /path/to/example
	* @exception    Javadoc-compatible, use as needed
	* @global       type $globalvarname 
		or
	* @global       type description of global variable usage in a function
	* @ignore
	* @internal     private information for advanced developers only
	* @param        type [$varname] description
	* @return       type description
	* @link         URL
	* @name         procpagealias
		or
	* @name         $globalvaralias
	* @magic        phpdoc.de compatibility
	* @package      package name
	* @see          name of another element that can be documented, produces a link to it in the documentation
	* @since        a version or a date
	* @static
	* @staticvar    type description of static variable usage in a function
	* @subpackage   sub package name, groupings inside of a project
	* @throws       Javadoc-compatible, use as needed
	* @todo         phpdoc.de compatibility
	* @var        type    a data type for a class variable
	* @version    version
	*/
function if_there_is_an_inline_source_tag_this_must_be_a_function()
{
	
}

/**
 * This function cleans up the passed string
 *
 * @access   public
 * @author   Paz
 *
 * @param    string   $string         The input string which will be parsed and cleaned up
 * @param    boolean  $escape         TRUE if the string should be escaped for DB query
 * @param    string   $allowed_tags   Specify tags which should not be stripped
 *
 * @return   string                 Returns stripped string
 *
 * @since    13-06-2005
 * @version  1.0
 *
 */
function cleanup_input_text ($string, $escape = FALSE,$allowed_tags = '') {

  $string = trim($string);
  $string = strip_tags($string, $allowed_tags);
  if ($escape == TRUE) {
  	$string = pg_escape_string($string);
  }
  $string = htmlspecialchars($string);
  
  return $string;
}

/**
 * Rewritten PHP5 function for PHP4
 *
 * @access   public
 * @author   Svilen <svilen@svilen.com>
 *
 * @param    array   $array   The input array containing the value of which the URL query string will be build. Example: array('var1' => 'value1', 'var2' => 'value2', ...)
 *
 * @return   string           Returns URL string ('var1=value1&var2=value2...')
 *
 * @since    15-06-2005
 * @version  1.0
 *
 */
if (!function_exists('http_build_query')) {
  function http_build_query($array = array()) {
  	$string = '';
    
    if (is_array($array) && !empty($array)) {
      foreach ($array as $key => $value) {
        $string .= urlencode($key).'='.urlencode($value);
        
        if (end($array) != $key) {
        	$string .= '&';
        }
      }
    }
    
    return $string;
  }
}

/**
 * This function return all sales with extensible details by order id
 *
 * update (Svilen) - returns prices for all currencies according to the store base currency
 * update (Svilen) - use of function getOrderDetails for retrieving necessary order's data
 * update (Svilen) - added patch for Free domain name with hosting plan
 * 15-09-2005 update (Svilen) - added patch for displaying correct amount when the currency of the order is not USD
 *
 *
 * @access   public
 * @author   Svilen <svilen@svilen.com>
 *
 * @param    resource   $handler   anyDB layer object handler 
 * @param    int        $orderId   order Id
 * @param    boolean    $currency  If all currencies should be calculated 
 *
 * @return   array      Returns all sales details
 *
 * @see      function getOrderDetails ($orderId, $dbHandler); anyDB handler
 * @see			 function getExchangeRate ($dbHandler, $currency1, $currency2)
 *
 * @since    15-09-2005
 * @version  1.4
 *
 */
function getSalesByOrderId ($dbHandler, $orderId, $currency = '', $exchangeRate = 1) {
	$salesDetails = array();
  $orderDetails = array();
  $storeDetails = array();
  $plansWithFreeDomain = array();
  $orderId = cleanup_input_text ($orderId, TRUE);
  $clientId = NULL;
  $storeId = NULL;
  $resellerId = NULL;
  $setDomainPrice = FALSE;
  $baseCurrency = '';
  $baseExchangeRate = !empty($exchangeRate) ? $exchangeRate : 1;
    
  $saleSelect = 's.sale_id as sale_id,
  							s.reseller_id as reseller_id,
                s.client_id as client_id,
                s.affiliate_id as affiliate_id,
                s.referer_id as referer_id,
                s.product_id as product_id,
                s.store_id as store_id,
                s.purchase_id as purchase_id,
                s.amount_total as amount_total,
                s.amount_wholesale as amount_wholesale,
                s.amount_affiliate as amount_affiliate,
                s.date as date,
                s.payed_reseller as payed_reseller,
                s.payed_affiliate as payed_affiliate,
                s.payed_referer as payed_referer,
                s.order_number as order_number,
                s.currency as currency,
                s.period as period,
                s.name as sale_name,
                s.type as sale_type,
                s.sale_period as sale_period,
                s.payment_method as payment_method,
                s.state as state,
                s.order_id as order_id,
                s.amount_vat as amount_vat,
                s.amount_fee as amount_fee,
                
                p.purchase_id as purchase_id,
                p.period as purchase_period,
                p.expire_date as purchase_expire_date,
                p.start_date as purchase_start_date,
                
                pr.product_id	as product_id,
                pr.name	as product_name,
                pr.store_id as product_store_id,
                pr.reseller_id as product_reseller_id,
                pr.type as product_type,
                pr.services as product_services,
                pr.price as product_price,
                pr.max_price as product_max_price,
                pr.wholesale as product_wholesale,
                pr.count as product_count,
                pr.life as product_life,
                pr.seq as product_seq,
                pr.state as product_state,
                pr.rp_product_id as product_rp_product_id,
                
                r.id as domain_id,
                r.flags as domain_flags,
                r.last_action as domain_last_action,
                r.sld as domain_sld,
                r.tld as domain_tld,
                r.registrantaddress1 as domain_registrantaddress1,
                r.registrantaddress2 as domain_registrantaddress2,
                r.registrantcity as domain_registrantcity,
                r.registrantcountry as domain_registrantcountry,
                r.registrantemailaddress as domain_registrantemailaddress,
                r.registrantfax as domain_registrantfax,
                r.registrantfirstname as domain_registrantfirstname,
                r.registrantlastname as domain_registrantlastname,
                r.registrantjobtitle as domain_registrantjobtitle,
                r.registrantorganizationname as domain_registrantorganizationname,
                r.registrantphone as domain_registrantphone,
                r.registrantpostalcode as domain_registrantpostalcode,
                r.registrantstateprovince as domain_registrantstateprovince,
                r.registrantstateprovincechoice as domain_registrantstateprovincechoice,
                r.numyears as domain_numyears,
                r.unlockregistrar as domain_unlockregistrar,
                r.renewname as domain_renewname,
                r.domainpassword as domain_domainpassword,
                r.ns1 as domain_ns1,
                r.ns2 as domain_ns2,
                r.comments as domain_comments
                ';
  
	if (empty($dbHandler)) {
  	trigger_error('getSalesByOrderId needs orderId', E_USER_ERROR);
    return FALSE;
  }
  
  // Retrieve order's data
  $orderDetails = getOrderDetails ($orderId, $dbHandler);

  if (!empty($orderDetails)) {
    $clientId = $orderDetails['client_id'];
    $storeId = $orderDetails['store_id'];
    $resellerId = $orderDetails['reseller_id'];
  }
  else {
  	return FALSE;
  }
  
  // Retrieve store's details
  $storeDetails = getStoreDetails($storeId, $dbHandler);
  
  // Get all plans with free domains
  if (!empty($storeDetails) && is_array($storeDetails)) {
  	$plansWithFreeDomain = $storeDetails['products']['domains_free'];
  }

  $query = 'SELECT '.$saleSelect.' FROM sales as s
              LEFT JOIN purchases as p ON (s.purchase_id = p.purchase_id)
              LEFT JOIN products as pr ON (p.product_id = pr.product_id)
              LEFT JOIN registerdomain as r ON (r.purchase_id = s.purchase_id) WHERE s.order_id = \''.$orderId.'\'';
  $dbHandler->query($query);
  
  if ($dbHandler->numRows() > 0) {
    $salesDetails = $dbHandler->getAll();
    $salesDetails = decodeDbStringsInArray($salesDetails, array('product_services', 'product_min_price', 'product_price', 'product_max_price', 'product_wholesale'));
    
    // Currency patch
    // We need to calculate the price for every currency
    // should be moved into function
    if (!empty($currency)) {  
      foreach ($salesDetails as $key => $value) {
      	if (is_array($value)) {
        	$baseCurrency = $value['currency'];
          
        	foreach ($value as $keyKey => $valueKey) {
          	// When we have a payment in a different currency thank you page displays the amount in USD, which is incorrect
          	if ($keyKey == 'amount_total') {
            	if ($currency != 'USD') {
              	$salesDetails[$key][$keyKey] = $salesDetails[$key][$keyKey] * $baseExchangeRate;
              }
            }
          
          	if (in_array($keyKey, array('product_price', 'product_min_price', 'product_max_price', 'product_wholesale'))) {  

              // Patch for Free domain name, currently it add the price of the first found domain on top of the plan's price
              // Should be changed according to the new ideia in ResellersPanel2
              if (!empty($plansWithFreeDomain[$value['product_id']][$value['period']]) AND in_array($value['product_id'], array_keys($plansWithFreeDomain))) {
              	$setDomainPrice = TRUE;

                // Let's get domain price
                $domainPrice = getDomainPrice ($salesDetails, $baseCurrency, $keyKey, $dbHandler, $storeId, $resellerId);
                
                // Let's add the domain price to the plan price
                if (!empty($domainPrice)) {
                	$salesDetails[$key][$keyKey][$domainPrice['period']][$baseCurrency] += $domainPrice['price'];
                  $valueKey[$domainPrice['period']][$baseCurrency] += $domainPrice['price'];
                }
                
                // Unset domain price if we have a domain name in the order
                if (!empty($domainPrice['sale_id'])) {
                	$salesDetails = setDomainsPrices ($salesDetails, $domainPrice['sale_id'], $keyKey, 0);
                }
              }
              // end: Patch for Free domain name
              
        			foreach ($valueKey as $keyValue => $valueValue) {
                // Patch if the necessary currency is not available
                if (!in_array($currency, array_keys($valueValue))) {
                 	$valueValue[$currency] = '';
                }
								// end: Patch if the necessary currency is not available
                
                foreach ($valueValue as $key1 => $value1) {  
                	if ($key1 != $baseCurrency) {
                		$salesDetails[$key][$keyKey][$keyValue][$key1] = getProductCurrencyPrice($dbHandler, $valueKey, $keyValue, $baseCurrency, $key1);
                  }
                }
              }
            }
         	}
        }
      }
    }
    // end: Currency patch
    
    return $salesDetails;
  }
  else {
  	return FALSE; 
  }
}

/**
 * This function return corrency exchange rate for given currencies
 *
 * @access   private
 * @author   Svilen <svilen@svilen.com>
 *
 * @param    resource   $dbHandler  anyDB layer object handler 
 * @param    string     $currency1  first currency
 * @param    string     $currency2  second currency 
 *
 * @return   string     Returns exchange rate
 *
 * @since    15-09-2005
 * @version  1.1
 *
 */
function getExchangeRate(&$dbHandler, $currency1 = 'USD', $currency2 = 'USD') {
	$currency1 = strtoupper(!empty($currency1) ? $currency1 : 'USD');
  $currency2 = strtolower(!empty($currency2) ? $currency2 : 'USD');
  
  $query = 'SELECT '.$dbHandler->escapeStr($currency2).' FROM currency WHERE curr = \''.$dbHandler->escapeStr($currency1).'\'';
  $dbHandler->query($query);
  
  return $dbHandler->getValue();
}

/**
 * This function return a domain price and period from a sales' array
 *
 * @access   private
 * @author   Svilen <svilen@svilen.com>
 *
 * @param    array   		$sales   				Sales details array 
 * @param    string     $baseCurrency   Base store currency string
 * @param    string     $priceType  		Price field name which should be processed
 * @param    resource   $dbHandler   		anyDB layer object handler 
 * @param    int        $storeId   			store Id
 * @param    boolean    $resellerId  		reseller's Id 
 *
 * @return   array      Returns domain price, period and sale_id
 *
 * @see      function decodeDbStringsInArray
 * @see      function returnDomainPriceInArray
 *
 * @since    30-06-2005
 * @version  1.0
 *
 */
function getDomainPrice ($sales, $baseCurrency, $priceType, $dbHandler, $storeId, $resellerId) {
	$domain = array();
	$period = 0;
  $price = 0;
  $storeId = cleanup_input_text ($storeId, TRUE);
  $resellerId = cleanup_input_text ($resellerId, TRUE);
  $domainDbDetails = array();
  
  // Map correct db field according to the price type (e.g. wholesale, retail...)
  switch ($priceType) {
  	case 'product_price':
    	$priceField = 'price';
    	break;
		case 'product_min_price':
    	$priceField = 'min_price';
    	break;
    case 'product_max_price':
    	$priceField = 'max_price';
    	break;
    case 'product_wholesale':
    	$priceField = 'wholesale';
    	break;
    default:
    	$priceField = 'price';
    	break;  
  }
  
	if (!empty($sales) && is_array($sales) && !empty($baseCurrency) && !empty($priceType)) {
    // Return domain price in sale array
    $domain = returnDomainPriceInArray($sales, $baseCurrency, $priceType);
        
    // Get domain price from the DB if there is no domain in the current order
    if (empty($domain['price'])) {
    	$query = 'SELECT p.'.$priceField.' as price FROM products as p
								WHERE p.reseller_id = \''.$resellerId.'\' AND p.store_id = \''.$storeId.'\' AND (p.type = \'domain\' OR p.type = \'registerdomain\') ORDER BY p.type ASC';
      $dbHandler->query($query);

      if ($dbHandler->numRows() > 0) {
        $domainDbPrice = $dbHandler->getNext();
        $domainDbPrice = decodeDbStringsInArray($domainDbPrice, array('price'));
        
        // Re-declare price values :) (for compatability)
        $domainDbPrice = $domainDbPrice['price'];
      }

      // assign domain details extracted from the DB
     	$domain = array('period' => $domain['period'], 'price' => $domainDbPrice[$domain['period']][$baseCurrency]);
    }
    
  }
  
  return $domain;
}

/**
 * This function return a domain price and period from a sales' array
 *
 * @access   private
 * @author   Svilen <svilen@svilen.com>
 *
 * @param    array   		$sales   				Sales details array 
 * @param    string     $baseCurrency   Base store currency string
 * @param    string     $priceType  		Price field name which should be processed
 *
 * @return   array      Returns domain price, period and sale_id
 *
 * @since    30-06-2005
 * @version  1.0
 *
 */
function returnDomainPriceInArray ($sales, $baseCurrency, $priceType) {
	$domain = array();
  
	foreach ($sales as $salesKey => $salesValue) {
  	if (in_array($salesValue['product_type'], array('domain', 'registerdomain'))) {
    	$period = $salesValue['period'];
    	$price = $salesValue[$priceType][$period][$baseCurrency];
      
      $domain = array ('period' => $period, 'price' => $price, 'sale_id' => $salesValue['sale_id']);
      break;
    }
    else {
    	$domain['period'] = $salesValue['period'];
    }
  }
  
  return $domain;
}

/**
 * This function sets a given price to a domain product in a given sales' array
 *
 * @access   private
 * @author   Svilen <svilen@svilen.com>
 *
 * @param    array   		$sales   				Sales details array 
 * @param    int		    $sale_id   			sale_id of the domain product, which should be processed
 * @param    string     $priceField  		Currency field which should be processed 
 * @param    float 			$price   				Price which should be set 
 *
 * @return   array      Returns sales' array
 *
 * @since    30-06-2005
 * @version  1.0
 *
 */
function setDomainsPrices ($sales, $sale_id, $priceField, $price = 0) {

  if (!empty($sales) && is_array($sales) && !empty($sale_id) && !empty($priceField)) {
  	foreach ($sales as $salesKey => $salesValue) {
    	if ($salesValue['sale_id'] == $sale_id) {
      	
        $sales[$salesKey][$priceField][$salesValue['period']][$salesValue['currency']] = $price;
        
        return $sales;
      }
    }
  }
  
}

/**
 * This function return all order details
 *
 * @access   public
 * @author   Svilen <svilen@svilen.com>
 *
 * @param    int        $orderId   order Id
 * @param    resource   $handler   anyDB layer object handler 
 * 
 * @return   array      Returns all order details
 *
 * @see      anyDB handler
 *
 * @since    30-06-2005
 * @version  1.0
 *
 */
function getOrderDetails ($orderId, $dbHandler) {
	$orderDetails = array();
  $orderId = cleanup_input_text ($orderId, TRUE);
  
  $orderSelect = 'o.order_id  as order_id,
									o.date as date,
                  o.order_number as order_number,
                  o.order_status as order_status,
                	o.company_id as company_id,
                  o.store_id as store_id,
                  o.reseller_id as reseller_id,
                  o.client_id as client_id,
                  o.affiliate_id as affiliate_id,
                  o.referer_id as referer_id,
                  o.payment_method as payment_method,
                  o.currency as currency,
                  o.client_company_name as client_company_name,
                  o.client_vat_num as client_vat_num,
                  o.client_firstname as client_firstname,
                  
                  o.client_lastname as client_lastname,
                  o.client_email as client_email,
                  o.client_address1 as client_address1,
                  o.client_address2 as client_address2,
                  o.client_city as client_city,
                  o.client_state as client_state,
                  o.client_zip as client_zip,
                  o.client_country as client_country,
                  
                  o.client_country as client_country,
                  o.client_phone as client_phone,
                  o.client_fax as client_fax,
                  o.ip as ip,
                  o.payment_exchange as payment_exchange,
                  o.payment_currency as payment_currency,
                  c.iso2 as iso2,
                  c.name as name
                ';
  
	if (empty($dbHandler)) {
  	trigger_error('getOrderDetails needs storeId', E_USER_ERROR);
    return FALSE;
  }
  
  $query = 'SELECT '.$orderSelect.' FROM orders o LEFT JOIN countries c ON (c.iso2 = o.client_country) WHERE order_id = \''.$orderId.'\'';
  $dbHandler->query($query);
   
  if ($dbHandler->numRows()) {
		$orderDetails = $dbHandler->getNext();
  }
  
  return $orderDetails;
}

/**
 * This function return all store details
 *
 * @access   public
 * @author   Svilen <svilen@svilen.com>
 *
 * @param    int        $storeId   store Id
 * @param    resource   $handler   anyDB layer object handler 
 * 
 * @return   array      Returns all store details
 *
 * @see      anyDB handler
 *
 * @since    30-06-2005
 * @version  1.0
 *
 */
function getStoreDetails ($storeId, $dbHandler) {
	$storeDetails = array();
  $storeId = cleanup_input_text ($storeId, TRUE);
  
  $storeSelect = 's.store_id as store_id,
									s.reseller_id as reseller_id,
                  s.title as title,
                  s.currency as currency,
                	s.language as language,
                  s.template as template,
                  s.header_type as header_type,
                  s.header_data as header_data,
                  s.footer_type as footer_type,
                  s.footer_data as footer_data,
                  s.menus as menus,
                  s.metatags as metatags,
                  s.contacts as contacts,
                  s.products as products,
                  s.name as name
                ';
  
	if (empty($dbHandler)) {
  	trigger_error('getStoreDetails needs storeId', E_USER_ERROR);
    return FALSE;
  }
  
  $dbHandler->query('SELECT '.$storeSelect.' FROM stores s WHERE store_id = \''.$storeId.'\'');
  
  if ($dbHandler->numRows()) {
		$storeDetails = $dbHandler->getNext();
    $storeDetails = decodeDbStringsInArray($storeDetails, array('menus', 'products'));
  }
  
  return $storeDetails;
}

/**
 * This function returns the correct price of a product according to a given currency
 *
 * @access   public
 * @author   Svilen <svilen@svilen.com>
 *
 * @param    object   $dbHandler   anyDB handler for db queries
 * @param    array    $priceArray  Product prices array
 * @param    integer  $period      Product period price
 * @param    string   $currency    Currency 
 *
 * @return   float    Returns product price
 *
 * @since    40-06-2005
 * @version  1.0
 *
 */
function getProductCurrencyPrice ($dbHandler, $priceArray, $period, $baseCurrency, $currency) {
	$price = 0;
  $exchangeRate = 1;
   
  // get exchange rate according to the given currency
  $dbHandler->query('SELECT * FROM currency WHERE curr =\''.strtoupper($baseCurrency).'\'');
	$result = $dbHandler->getNext();
  $exchangeRate = $result[strtolower($currency)];
  
  if (!empty($priceArray[$period][$baseCurrency])) {
  	$price = $priceArray[$period][$baseCurrency] * $exchangeRate;
  }
  else {
  	if (is_array($priceArray)) {
      foreach ($priceArray[$period] as $key => $value) {
      	if (!empty($value)) {
        	$dbHandler->query('SELECT * FROM currency WHERE curr =\''.strtoupper($key).'\'');
          $result = $dbHandler->getNext();
          $exchangeRate = $result[strtolower($currency)];
          $price = $value * $exchangeRate;

          break;
        }
      }
    }
  }
  
  return $price;
}

/**
 * This function return base64 decoded and unserialized db strings from array (Should be removed those storage method from the DB)
 *
 * @access   public
 * @author   Svilen <svilen@svilen.com>
 *
 * @param    array   $DbArray     	 Encoded strings array
 * @param    array   $stringsArray   Which keys/values should be decoded
 *
 * @return   array    Returns decoded string
 *
 * @since    20-06-2005
 * @version  1.0
 *
 */
function decodeDbStringsInArray ($array, $stringsArray)
{
	foreach ($array as $key => $value)
	{
		if (!empty($value))
		{
			if (is_array ($value))
			{
        $array[$key] = decodeDbStringsInArray ($value, $stringsArray);
			}
			else
			{
        if (in_array($key, $stringsArray)) {
        	$array[$key] = decodeDbStrings($value);
        }
			}
		}
	}

	return $array;
}

/**
 * This function return base64 decoded and unserialized db strings
 *
 * @access   public
 * @author   Svilen <svilen@svilen.com>
 *
 * @param    string   $string   Encoded string
 *
 * @return   array    Returns decoded array
 *
 * @since    02-03-2006
 * @version  1.0
 *
 */
function decodeDbStrings ($string)
{
	if (empty($string)) {
		return FALSE;
	}
	
	$result = unserialize(base64_decode($string));
  
	return $result;
}

/**
 * This function return payment method by payment processor order number
 * returns:
 * 	worldpay 				- for WorldPay orderId
 *   paypal 				- for PayPal orderId
 *   2co 						- for 2CheckOut orderId
 *   2co_recurring 	- for 2CheckOut recurring
 *   clickbank 			- for ClickBank orderId
 *   wallet 				- for Wallet 
 *
 * example usage:
 * 	 $paymentMethod = paymentProcessorByOrderNumber('2UU27251BD0871929');
 *
 * ex. order numbers:
 * 	 119486307  WorldPay
 *   1932942359  2Checkout.com
 *   1928698352  2Checkout.com
 *   64790 - 24056202  2Checkout.com - old
 *   64790 - R52401680  2Checkout.com reccuring
 *   2UU27251BD0871929  PayPal
 *   4F5670616B596031N  PayPal
 *   ZLVGH8D0 - CLICKBANK
 *   GRTXK5B0 - CLICKBANK   
 *   5W829818LA967132Cref1 - Refund
 *   wallet234 - Wallet
 *
 * @access   public
 * @author   Svilen <svilen@svilen.com>
 *
 * @param    string  $orderId     	 Payment processor order number
 *
 * @return   string  Returns payment processor
 *
 * 
 * @since    27-06-2005
 * @version  1.1
 *
 */
function paymentProcessorByOrderNumber ($orderId = '') {
	$orderId = trim($orderId);
  $method = 'unknown';
    
  if (!empty($orderId)) {
    $refund = substr_count($orderId, 'ref');
    $wallet = substr_count($orderId, 'wallet');
    
    // If the orderId is being refunded one
    if ($refund > 0) {
    	$orderId = substr($orderId, 0, strpos($orderId, 'ref'));
    }
    
    $length = strlen($orderId);
    $numeric = (bool) is_numeric($orderId);
    $dash = substr_count($orderId, '-');
    $Rletter = substr_count($orderId, 'R');
    
    switch (true) {
    	case ($wallet > 0):
      	// Wallet
      	$method = 'wallet';
      	break;
      case ($dash == 1 && $Rletter == 1):
      	// 2CheckOut recurring
       	$method = '2co_recurring';
        break;
    	case ($dash == 1 && $Rletter != 1):
      	// 2CheckOut
       	$method = '2co';
        break;
      case ($numeric === FALSE && $length == 9 && $Rletter == 1):
      	// 2CheckOut Old
        $method = '2co_recurring';
      	break;
      case ($numeric === TRUE && $length == 8):
      	// 2CheckOut Old
        $method = '2co';
      	break;
      case ($numeric === TRUE && $length == 10):
      	// 2CheckOut
      	$method = '2co';
        break;
      case ($numeric === TRUE && $length == 9):
      	// WorldPay
        $method = 'worldpay';
      	break;
      case ($numeric === FALSE && $length == 17):
       	// PayPal Id
        $method = 'paypal';
        break;
      case ($numeric === FALSE && $length == 8):
      	// ClickBank
      	$method = 'clickbank';
      	break;
    }  
  }
  return $method;
}

/**
 * price_format function returns formated price string
 *
 * @access   public
 * @author   Svilen <svilen@svilen.com>
 *
 * @param string     $price      Price
 * @param character  $currency   USD, GBP, BGN, EUR, AUD, CAD
 *
 * @return string    Formatted price
 *
 * @since    19-08-2005
 * @version  1.0
 *
 */
function price_format($price, $currency = 'USD', $suffix = true, $decimals = 2, $decpoint = '.', $thousandsep = '', $customDevide = 1)
{ 
	
  if (!empty($customDevide)) {
   	$price = $price / $customDevide;      
  }
  
  $price = number_format($price, $decimals, $decpoint, $thousandsep);
  
	switch ($currency) {
  	case 'AUD':
    	$price = '$'.$price;
    	break;
    case 'CAD':
    	$price = '$'.$price;
    	break;
    case 'BGN':
    	$price = $price;
    	break;
    case 'EUR':
    	$price = '&euro;'.$price;
    	break;
    case 'GBP':
    	$price = '&pound;'.$price;
    	break;
    default: // USD
    	$price = '$'.$price;
    	break;
  }
  
  // Let's concat the currency suffix
  if ($suffix == true) {
  	$price .= ' ('.$currency.')';
  }
  
  return $price;
}

?>